<?php
namespace app\common\service\impl;
use app\common\client\MessageClient;
use app\common\client\SaiKaSMS;
use app\common\enums\ResultEnum;
use app\common\exception\ZeduException;
use app\common\model\Admin;
use app\common\model\Cars;
use app\common\model\Terminal;
use app\common\service\MessageService;
use app\common\client\IotCloudClient;
use app\common\model\CarsInfo;
use think\facade\Cache;
use think\facade\Log;

class MessageServiceImpl implements MessageService
{
    protected $messageClient;
    protected $saiKaSMS;
    protected $cars;
    protected $terminal;
    protected $iotClient;
    protected $carsInfo;
    
    public function __construct(MessageClient $messageClient,SaiKaSMS $saiKaSMS,Cars $cars,Terminal $terminal,IotCloudClient $iotClient,CarsInfo $carsInfo)
    {
        $this->messageClient = $messageClient;
        $this->saiKaSMS = $saiKaSMS;
        $this->cars = $cars;
        $this->terminal = $terminal;
        $this->iotClient = $iotClient;
        $this->carsInfo = $carsInfo;
    }
  
    public function send(String $cardCode, String $content)
    {
        $adminId = session('admin.id');
        $name = Admin::where(['id'=>$adminId])->value('nick_name');
        $simCard = $this->cars->where(['cardcode'=>$cardCode])->value('sim_card');
        if($simCard == 1376920004){
            $data = $this->messageClient->sendMessage($cardCode, $content,$name,'send_sms');
            
        }elseif ($simCard == 1376920005){
          
            $data = $this->messageClient->sendMessage($cardCode, $content,$name,'gt_send_sms');
            
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'卡商未知']);
        }
        
        if($data === false){
            return false;
        }
        if($data['code'] == 0){
            return true;
        }else{
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$data['msg']]);
        }
    }
    
    public function cardStatus(String $simId)
    {
        $cars = $this->cars->where(['sim_id'=>$simId])->field('car_sn,car_unique_id,equipment_id,sim_id,cardcode,supplier_no,sim_card')->find();
        $cardData = [];
        
        if($cars['sim_card'] == 1376920004){      
            $data = $this->messageClient->cardStatus($simId);
            if($data === false){
                return false;
            }
            
            if($data['code'] == 0 && !empty($data['data'])){
                $cardData['card'] = $data['data']['cardStatus'];
            }
            
        }elseif ($cars['sim_card'] == 1376920005) {
            $data = $this->saiKaSMS->realTime($cars['cardcode']);
            if(!empty($data)){
                $arr = json_decode($data,true);
                if($arr['status'] == 0000){
                    $cardData['card'] = $arr['result'][0];
                }else{
                    throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$arr['message']]);
                }
                
            }else{
                return false;
            }
           
        }
         $cardData['cars'] = $cars;
         return $cardData; 
    }
    
    public function smsup(int $page, int $size,String $search)
    {
        $data = $this->messageClient->smsUp($page, $size, $search);
        if($data === false){
            return false;
        }
        
        if(!empty($data) && $data['code'] == 0){
            return $data['data'];
            
        }else{
            return false;
        }
    }

    public function smsDown(int $page,int $size,String $search){
        $data = $this->messageClient->smsDown($page,$size,$search);
        if($data === false){
            return false;
        }
        
        if(!empty($data) && $data['code'] == 0){
            return $data['data'];
            
        }else{
            return false;
        }
    }
    
    public function traffic(String $simId,String $simCard)
    {
        $cardData = [];
        if($simCard == 1376920004){
            $data = $this->messageClient->cardFlow($simId);
            
            if($data === false){
                return false;
            }
            
            if($data['code'] == 0 && !empty($data['data']['cardFlowInfos'])){
                $cardData = $data['data']['cardFlowInfos'][0];
            }else{
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$data['msg']]);
            }
            
        }else if($simCard == 1376920005){
            $data = $this->saiKaSMS->cardFlow($simId);  
            if(!empty($data)){
                $arr = json_decode($data,true);
                if($arr['status'] == 0000 && !empty($arr['result'])){
                    $cardData = $arr['result'][0];
                }else{
                    throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$arr['message']]);
                }
                
            }else{
                return false;
            } 
        }
        
         return $cardData;
    }
    
    public function packageInfo(String $simId, String $simCard)
    {
        $cardData = [];
        if($simCard == 1376920004){
            $data = $this->messageClient->packageInfo($simId);
            if($data === false){
                return false;
            }
            if($data['code'] == 0 && !empty($data['data']['cardOfferDetail'])){
                $cardData = $data['data']['cardOfferDetail'];
            }else{
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$data['msg']]);
            }
            
        }else if($simCard == 1376920005){
            $data = $this->saiKaSMS->packageInfo($simId);
            
            if(!empty($data)){
                $arr = json_decode($data,true);
                
                if($arr['status'] == 0000 && !empty($arr['result'])){
                    $cardData = $arr['result'][0];
                }else{
                     throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$arr['message']]);
                }
                
            }else{
                return false;
            }
        }
        
        return  $cardData;
    }
    
    public function upgrade(int $id)
    {
        $data =[];
        $adminId = session('admin.id');
        $name = Admin::where(['id'=>$adminId])->value('nick_name');
        $cars = $this->cars->field('sim_card,band_status,car_unique_id,cardcode,equipment_id')->get(['car_id'=>$id]);
        if($cars['band_status'] == 1){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'车辆未解绑']);
        }
        
        $terminal = $this->terminal->where(['equipment_id'=>$cars['equipment_id']])->field('id,status')->find();
        if($terminal['status'] !=1){
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'设备未注册']);
        }
        
        $arr = $this->iotClient->queryDetails($cars['equipment_id']);
        
        if($arr == false){
            return false;
        }
        
        if(!empty($arr) && $arr['result']==0){
            $data['productKey'] = $arr['data'][0]['data']['productKey'];
            $data['deviceSecret'] = $arr['data'][0]['data']['deviceSecret'];
            $content = '#836927,JCSZIOT:'.$data['productKey'].$data['deviceSecret'].'1883.iot-as-mqtt.cn-shanghai';
            
            if($cars['sim_card'] == 1376920004){
                $data = $this->messageClient->sendMessage($cars['cardcode'], $content, $name, 'send_sms');
            }elseif ($cars['sim_card'] == 1376920005) {
                $data = $this->messageClient->sendMessage($cars['cardcode'], $content, $name, 'gt_send_sms');
            }else{
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>'卡商未知']);
            }
            
            if($data === false){
                return false;
            }
            if($data['code'] == 0){
                $res = $this->updateData($cars['car_unique_id']);
                if($res){
                    return true;
                }else{
                    return false;
                }
                
            }else{
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$data['msg']]);
            }
        }
    }

    public function updateData($vin) {
        $this->cars->startTrans();
        try {
             $this->cars->save(['supplier_no'=>1376920003],['car_unique_id'=>$vin]); 
             
        } catch (\Exception $e) {
            Log::record('[ cars表更新失败 ]:'.$e->getMessage(),'error');
            $this->cars->rollback();
            return false;
        }
        if($this->cars->update_time){
            try {
                $this->carsInfo->save(['supplier_no'=>1376920003],['car_unique_id'=>$vin]); 
                $this->cars->commit();
            } catch (\Exception $e) {
                Log::record('[ carsInfo表更新失败 ]:'.$e->getMessage(),'error');
                $this->cars->rollback();
                return false;
            }
        }else{
            $this->cars->rollback();
            return false;
        }
        return true;
    }
    
    public function intercept(int $id, int $type)
    {
        $cacheData = Cache::get($id);
        $status = false;
        switch ($type) {
            case 1:
            case 2:
                $lock = time() - 30;
                if( empty($cacheData['ignite']) || $cacheData['ignite'] < $lock){
                    $status =true;
                    $cacheData['ignite'] =time();
                }
            break;
            case 3:
            case 10:
                $lock = time() - 30;
                if( empty($cacheData['lock']) || $cacheData['lock'] < $lock){
                    $status =true;
                    $cacheData['lock'] =time();
                }
                break;
            case 4:
                $lock = time() - 30;
                if( empty($cacheData['upgrade']) || $cacheData['upgrade'] < $lock){
                    $status =true;
                    $cacheData['upgrade'] =time();
                }
                break;
            case 5:
            case 6:
                $lock = time() - 30;
                if( empty($cacheData['restart']) || $cacheData['restart'] < $lock){
                    $status =true;
                    $cacheData['restart'] =time();
                }
                break;
            case 7:
            case 8:
                $lock = time() - 30;
                if( empty($cacheData['exchange']) || $cacheData['exchange'] < $lock){
                    $status =true;
                    $cacheData['exchange'] =time();
                }
                break;
            case 11: 
                $lock = time() - 30;
                if( empty($cacheData['message']) || $cacheData['message'] < $lock){
                    $status =true;
                    $cacheData['message'] =time();
                }
                break;
            case 12:
                $lock = time() - 30;
                if( empty($cacheData['analytic']) || $cacheData['analytic'] < $lock){
                    $status =true;
                    $cacheData['analytic'] =time();
                }
                break;
            case 13:
                $lock = time() - 30;
                if( empty($cacheData['vehicleMess']) || $cacheData['vehicleMess'] < $lock){
                    $status =true;
                    $cacheData['vehicleMess'] =time();
                }
                break;
            case 14:
            case 15:
                $lock = time() - 30;
                if( empty($cacheData['APN']) || $cacheData['APN'] < $lock){
                    $status =true;
                    $cacheData['APN'] =time();
                }
                break;
            case 16:
                $lock = time() - 30;
                if( empty($cacheData['system']) || $cacheData['system'] < $lock){
                    $status =true;
                    $cacheData['system'] =time();
                }
                break;
            default:
            break;
        }
        
        Cache::set($id,$cacheData);
        return $status;
    }
    
    public function queryStatus(String $sendKey)
    {
        $data = $this->saiKaSMS->querySendStatus($sendKey);
        if(!empty($data)){
            $arr = json_decode($data,true);
            
            if($arr['status'] == 0000){
                return $arr['result'][0];
            }else{
                throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$arr['message']]);
            }
            
        }else{
            return false;
        }
    }


}

